use std::sync::{mpsc::Sender, Arc};

use crate::managers::resource_manager::ResourceManagerExt;
use egui::{include_image, Color32, Image, Layout, Pos2, Rect, Vec2};
use QcUI::{
    component::{Label, UiNodeTrait},
    core::context::UiContext,
};

use crate::{
    components::dock::DockView,
    core::{context::Context, message::EditorMessage},
};

use super::ResFile;

#[derive(Debug)]
pub struct NavPanel {
    context: Arc<Context>,
    editor_sender: Sender<EditorMessage>,
    current_scene: ResFile,
    scenes: Vec<ResFile>,
}

impl DockView for NavPanel {
    fn render(&mut self, ctx: &mut UiContext, show_tab: bool) {
        ctx.ui.vertical_centered(|ui| {
            let start = Image::new(include_image!("../../assets/icon/start.svg"))
                .tint(Color32::LIGHT_YELLOW);

            let rect = Rect::from_min_size(
                Pos2::new(
                    (ui.available_width() - 200.) / 2.,
                    (ui.available_height() - 200.) / 2.,
                ),
                Vec2::new(200., 200.),
            );

            let ui = &mut ui.child_ui(rect, egui::Layout::left_to_right(egui::Align::Center));

            ui.horizontal_centered(|ui| {
                egui::ComboBox::from_id_source(egui::Id::new("scene_select"))
                    .selected_text(&self.current_scene.file_name)
                    .height(120.)
                    .show_ui(ui, |ui| {
                        for file in self.scenes.iter() {
                            ui.selectable_value(
                                &mut self.current_scene,
                                file.clone(),
                                &file.file_name,
                            );
                        }
                    });
                ui.add_space(10.);
                let start_button = egui::Button::image(start).small();
                let result = ui.add_sized([25., 25.], start_button);
                if result.clicked() {
                    self.editor_sender
                        .send(EditorMessage::PlayGame(self.current_scene.get_path()))
                        .unwrap();
                }
            });
        });
    }
}

impl NavPanel {
    pub fn new(context: Arc<Context>, editor_sender: Sender<EditorMessage>) -> Self {
        let context_ref = context.clone();
        let config = context_ref.project_config.try_read().unwrap();
        let config = config.as_ref().unwrap();

        let current_scene = context
            .resource_manager
            .get_file_by_name(&config.scene)
            .unwrap();

        let scenes = context.resource_manager.get_all_scene();

        Self {
            context,
            editor_sender,
            current_scene,
            scenes,
        }
    }
}
